window.lkg = {};
var baseUrl = "http://121.43.104.166:8085";

(function($, lkg) {
	var IMAGE_DOWNLOAD = "IMAGE_DOWNLOAD";
	var IMAGE_DOWNLOAD_WHEN_WIFI = "true";

	var UNITS = {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	};
	//毫秒换算
	lkg.humanize = function(milliseconds) {
		var humanize = '';
		$.each(UNITS, function(unit, value) {
			if (milliseconds >= value) {
				humanize = Math.floor(milliseconds / value) + unit + '前';
				return false;
			}
			return true;
		});
		return humanize || '刚刚';
	};
	//日期格式化
	lkg.format = function(milliseconds) {
		var diff = Date.now() - milliseconds;
		if (diff < UNITS['天']) {
			return lkg.humanize(diff);
		}
		var date = new Date(milliseconds);
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' + _format(date.getHours()) + ':' + _format(date.getMinutes());
	};
	lkg.toggleDownloadWhenWifi = function(whenWifi) {
		if (whenWifi) {
			plus.storage.setItem(IMAGE_DOWNLOAD, IMAGE_DOWNLOAD_WHEN_WIFI);
		} else {
			plus.storage.removeItem(IMAGE_DOWNLOAD);
		}
	};
	lkg.isDownloadWhenWifi = function() {
		return !!plus.storage.getItem(IMAGE_DOWNLOAD);
	};
	//是否登录
	lkg.isLogin = function() {
		var userToken = plus.storage.getItem(_user_token);
		if (userToken && userToken != "") {
			return true;
		} else {
			return false;
		}
	};
	//图片自适应高度
	lkg.autoHeight = function(element) {
		var width = element.offsetWidth;
		var height = width * 0.67;
		return height + "px";
	};
	//数组去重
	lkg.unique = function(arr) {
		// 遍历arr，把元素分别放入tmp数组(不存在才放)
		var tmp = [];
		for (var i = 0; i < arr.length; i++) {
			//该元素在tmp内部不存在才允许追加
			if (tmp.indexOf(arr[i]) === -1) {
				tmp.push(arr[i]);
			}
		}
		return tmp;
	};
	//页面跳转
	lkg.detail = function(id) {
		plus.storage.setItem("id", id);
		mui.openWindow({
			url: 'news-details.html',
			id: 'news-details.html'
		});
	};
}(mui, lkg));

/**
 * 默认打开软键盘
 * @param options{
 *   input: '#nickname' // 容器节点
 * }
 */
function open_soft_keyboard(options){
    if(plus.os.name == 'iOS'){
        setTimeout(function(){
            var wv_current = plus.webview.currentWebview().nativeInstanceObject();
            wv_current.plusCallMethod({"setKeyboardDisplayRequiresUserAction":false});
            document.querySelector(options['input']).focus();
        }, 330);
    }else{
        // 因为安卓autofocus只有4.0版本以上才支持，所以这里使用native.js来强制弹出
        setTimeout(function(){
            // 在执行的时候需要让当前webview获取焦点
            var wv_current = plus.android.currentWebview();
            plus.android.importClass(wv_current);
            wv_current.requestFocus();

            var Context = plus.android.importClass("android.content.Context");
            var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
            var main = plus.android.runtimeMainActivity();
            var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
            document.querySelector(options['input']).focus();
        }, 330);
    }
}

//日期格式化函数+调用方法
Date.prototype.format = function(format) {
	var o = {
		"M+": this.getMonth() + 1, //month
		"d+": this.getDate(), //day
		"h+": this.getHours(), //hour
		"m+": this.getMinutes(), //minute
		"s+": this.getSeconds(), //second
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
		"S": this.getMilliseconds() //millisecond
	};
	if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
		(this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
	}
	return format;
};

//夜间模式
(function() {
	if (document.getElementById("index")) {
		var index = document.getElementById("index").value;
	}
	document.addEventListener("plusready", plusReady, false);

	function plusReady() {
		var nightMode = plus.storage.getItem("modeFlag");

		//判断是否切换成了夜间模式
		if (nightMode) {
			var head = document.getElementsByTagName('head')[0];
			var link = document.createElement('link');
			var cssHref = null;

			//是否是首页
			if (index == 0) {
				cssHref = "css/night-mode.css";
			} else {
				cssHref = "../css/night-mode.css";
			}
			link.id = "night_style";
			link.rel = 'stylesheet';
			link.href = cssHref;
			head.appendChild(link);
			plus.navigator.setStatusBarStyle("UIStatusBarStyleBlackOpaque");
			plus.navigator.setStatusBarBackground("#333");
		} else {
			if (document.getElementById("night_style")) {
				var night = document.getElementById("night_style");
				night.parentNode.removeChild(night);
			}
		}
	}
}());

//字体大小
(function() {
	document.addEventListener("plusready", plusReady, false);

	function plusReady() {
		var fontSize = plus.storage.getItem("fontFlag");
		//		alert(fontSize);

		if (document.querySelector("#textBody")) {
			var textBody = document.querySelector("#textBody");
			var textItems = textBody.querySelectorAll("p");
			console.log(textItems[0].innerText);
			//判断字体大小为多少号
			switch (fontSize) {
				case "1":
					textSize(12); //小
					break;
				case "2":
					textSize(16); //中
					break;
				case "3":
					textSize(20); //大
					break;
			}

			function textSize(size) {
				for (var i = 0; i < textItems.length; i++) {
					textItems[i].style.fontSize = size + "px";
				}
			}
		}
	}
}());